// packageA/pages/cashService/operator/bagFillin/bagFillin.js
import Dialog from '../../../../miniprogram_npm/@vant/weapp/dialog/dialog'
const { request } = require('../../../../utils/request');
const { imgPath } = require('../../../../utils/request');
const { formatDay } = require('../../../../utils/util');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    imgPath: imgPath,
    id: '',
    qrcodeNo: '',
    inputAmount: '', //金额
    realCashAmount: '',
    accountOptions: [],
    originAccountOptions: [],
    haveBeenBind: [],
    enableAccountPicker: false,
    accountIndex: '',
    abstractOptions: [],
    abstractIndex: '',
    ifshowPicker: false,
    pickerType: '',
    showBtn: true,
    currentStr: '', // yyyy-mm-dd
    currentDate: new Date().getTime(),  // 毫秒
    minDate: '',
    maxDate: '',
    jjCode:'', // 前两位代表月份，第3位数字按款项来源对应数字，4-7位代码加油站编码后四位，最后两位代表缴款日期
    formatter(type, value) {
      if (type === 'year') {
        return `${value}年`;
      }
      if (type === 'month') {
        return `${value}月`;
      }
      return `${value}日`;
    },
    showMoreField: false,
    more: '',
    addFlag: false,
    station: wx.getStorageSync('userInfo').stationName,
    staffOptions: [],
    staffIndex: '',

    abstractText: '',
    bagInfo: {},

    submitting: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options)
    //新建箱包
    if (options.newBag) {
      wx.setNavigationBarTitle({
        title: '新建箱包'
      })
    }else{
      wx.setNavigationBarTitle({
        title: '箱包详情'
      })
    }
    // 编辑箱包时传参
    var tempDateStr = formatDay(this.data.currentDate)
    if (options.bagInfo) {
      let bagInfo = JSON.parse(options.bagInfo)
      console.log(bagInfo)
      let tempStr = bagInfo.payDate.slice(0, 4) + '/' + bagInfo.payDate.slice(4, 6) + '/' + bagInfo.payDate.slice(6, 8)
      tempDateStr = formatDay(tempStr)
      this.setData({
        bagInfo: bagInfo,
        inputAmount: bagInfo.inputAmount,
        realCashAmount: bagInfo.realCashAmount,
        id: bagInfo.id,
        qrcodeNo: bagInfo.qrcodeNo,
        currentDate: new Date(Date.parse(tempDateStr)).getTime()
      })
    }
    let tempDate = new Date().getTime()
    this.setData({
      minDate: new Date(tempDate - 7 * 24 * 60 * 60 * 1000).getTime(),
      maxDate: new Date().getTime(),
      currentStr: tempDateStr
    })

    this.fetchFundsourcelist()
    // this.fetchAccountlist()
    this.fetchStafflist()
  },
  /**
   * 退回的箱包重新提交到清分公司
   */
  clickSub(){
    if (this.data.submitting) {
      return
    }
    console.log('提交到清分公司')
    var queryData = {
      id: this.data.id,
      qrcodeNo: this.data.qrcodeNo,
      accountId: this.data.accountOptions[this.data.accountIndex].id,
      inputAmount: this.data.inputAmount,
      realCashAmount: this.data.realCashAmount,
      payDate: this.data.currentStr.replace(/-/g, ''), // 8位
      fundType: !this.data.showMoreField ? 0 : this.data.addFlag ? 2 : 1,
      fundId: this.data.abstractOptions[this.data.abstractIndex].id,
      fundName: this.data.more ? this.data.more : '',
      actPayerId: this.data.staffIndex != this.data.staffOptions.length - 1 ? this.data.staffOptions[this.data.staffIndex].id : '',
      jjCode:this.data.jjCode
    }
    this.setData({ submitting: true })
    request('/smsk/wechat/baginfo/return/update', 'POST', queryData).then(res => {
      // console.log(res.data)
      this.setData({ submitting: false })
      if (res.data.code === 0) {
        wx.showToast({
          title: '提交成功',
          icon: 'success'
        })
        setTimeout(() => {
          wx.setStorageSync('tempTabId', '0')
          wx.navigateBack({
            delta: 1,
          })
        }, 1500)
      } else {
        // console.log(res.data)
        wx.showToast({
          title: '保存失败',
          icon: 'error'
        })
      }
    })
  },
  /**
   * 获取账户列表
   */
  fetchAccountlist() {
    var that = this
    request('/smsk/wechat/baginfo/accountlist', 'GET').then(res => {
      if (res.data.code === 0) {
        var tempIndex = ''
        // 如果是编辑箱包模式，找到所选账号在选项中的index用于选择器及展示
        if (that.data.bagInfo) {
          tempIndex = res.data.data.findIndex((item) => {
            return item.id === that.data.bagInfo.accountId
          })
        }
        console.log(tempIndex);
        this.setData({
          originAccountOptions: res.data.data,
          accountOptions: res.data.data,
          accountIndex: tempIndex
        })
        console.log(this.data.accountIndex)
        // 维护已被绑定了固定项目的收款户名、账号信息
        let tmpBeenBind = []
        this.data.originAccountOptions.forEach((account)=>{
          if (account.fundId != null) {
            tmpBeenBind.push(account.fundId)
          }
        })
        this.setData({
          haveBeenBind: tmpBeenBind
        })
        // 编辑模式也需过滤收款账户
        if (that.data.bagInfo) this.filterAccount(tempIndex)
      } else {
      }
    })
  },
  /**
   * 获取项目列表
   */
  fetchFundsourcelist() {
    var that = this
    request('/smsk/wechat/baginfo/fundsourcelist', 'GET').then(res => {
      console.log(res.data)
      if (res.data.code === 0) {
        // 如果是编辑箱包模式，找到所选项目在选项中的index用于选择器及展示
        var tempIndex = ''
        var tempShow = false
        var tempMore = ''
        if (JSON.stringify(that.data.bagInfo) !== '{}') {
          // 找选项
          tempIndex = res.data.data.findIndex((item) => {
            return item.fundName === that.data.bagInfo.fundName
          })
          console.log(tempIndex)
          // 未找到选项
          if (tempIndex === -1) {
            tempIndex = res.data.data.length
            tempShow = true
            tempMore = that.data.bagInfo.fundName
          }
        }

        // 添加一个“其他”选项
        let tempOptions = res.data.data
        tempOptions.push({
          id: '',
          fundName: '其他'
        })
        this.setData({
          abstractOptions: tempOptions,
          abstractIndex: tempIndex,
          showMoreField: tempShow,
          more: tempMore
        })
        this.fetchAccountlist()
        if (this.data.bagInfo) {
          this.formatAbs()
        }
      } else {
      }
    })
  },
  // 生成款项来源
  formatAbs() {
    var that = this
    if (this.data.abstractIndex !== '') {
      let tempDate = new Date(this.data.currentDate)
      // 如果是预缴款
      if (this.data.abstractOptions[that.data.abstractIndex].fundName.indexOf('预') != -1 || (this.data.showMoreField && this.data.more.indexOf('预') != -1)) {
        tempDate = new Date(this.data.currentDate)
      }
      let tempM = tempDate.getMonth() + 1 + '',
        tempD = tempDate.getDate() + '',
        tempTimeStr = this.addZero(tempM) + this.addZero(tempD)
      console.log(tempDate)
      if (this.data.showMoreField) {
        // 选择“其他”
        if (this.data.more) {
          this.setData({
            abstractText: wx.getStorageSync('userInfo').stationName + this.data.more + tempTimeStr
          })
        } else {
          this.setData({
            abstractText: ''
          })
        }
      } else {
        console.log(this.data.abstractOptions)
        this.setData({
          abstractText: wx.getStorageSync('userInfo').stationName + this.data.abstractOptions[that.data.abstractIndex].fundName + tempTimeStr,
          jjCode: this.addZero(tempM) + this.data.abstractOptions[that.data.abstractIndex].fundValue + wx.getStorageSync('userInfo').stationCode.substr(-4,4) + this.addZero(tempD)
        })
      }
    } else {
      this.setData({
        abstractText: ''
      })
    }
  },
  //补零操作
  addZero(num) {
    if (parseInt(num) < 10) {
      num = '0' + num;
    }
    return num;
  },
  showPicker(e) {
    console.log(this.data.abstractIndex)
    wx.hideKeyboard()
    if (e.currentTarget.dataset.type == 'accountName' || e.currentTarget.dataset.type == 'accountNo') {
      //!this.data.enableAccountPicker || this.data.abstractIndex == ''
      if (!this.data.enableAccountPicker) {
        wx.showToast({
          title: '请先选择项目',
          'icon': 'none'
        })
      }
      else {
        this.setData({
          ifshowPicker: true,
          pickerType: e.currentTarget.dataset.type,
          showBtn: false
        })
      }
    } else {
      this.setData({
        ifshowPicker: true,
        pickerType: e.currentTarget.dataset.type,
        showBtn: false
      })
    }
  },
  cleanStaff() {
    this.setData({
      ifshowPicker: false,
      pickerType: '',
      staffIndex: ''
    })
  },
  closePicker() {
    this.setData({
      ifshowPicker: false,
      pickerType: '',
      showBtn: true
    })
  },
  onPickerConfirm(e) {
    if (this.data.pickerType === 'accountNo' || this.data.pickerType === 'accountName') {
      this.setData({
        accountIndex: e.detail.index
      })
    } else if (this.data.pickerType === 'date') {
      this.setData({
        currentDate: e.detail,
        currentStr: formatDay(e.detail)
      })
    } else if (this.data.pickerType === 'staff') {
      this.setData({
        staffIndex: e.detail.index,
      })
    } else {
      this.setData({
        abstractIndex: e.detail.index,
        showMoreField: this.data.abstractOptions.length - 1 == e.detail.index
      })
      this.filterAccount('confirm')
    }
    // todo 这个判断待定
    this.formatAbs()
    this.closePicker()
  },
  // 根据所选项目过滤户名及账号
  filterAccount(e) {
    let selectedAccountName;
    if(e=='confirm') console.log("从选择弹窗中点击确认按钮进入")
    else {
      console.log("新建/编辑箱包进入")
      console.log(e)
      console.log(this.data.originAccountOptions[e])
      selectedAccountName = this.data.originAccountOptions[e].accountName
    }
    console.log(this.data.abstractOptions[this.data.abstractIndex].id)
    console.log(this.data.originAccountOptions)
    // 根据所选项目，查询是否被绑定了收款户名和账号
    // this.setData({
    //   accountOptions: this.data.originAccountOptions.filter((account)=>{
    //     return account.fundId == this.data.abstractOptions[this.data.abstractIndex].id
    //   })
    // })
    this.setData({
      accountOptions: this.data.originAccountOptions.filter((account)=>{
        if(account.fundId != null)
        return account.fundId.indexOf(this.data.abstractOptions[this.data.abstractIndex].id) != -1
      })
    })
    // this.data.accountOptions.length==0,说明:
    // 所选项目未设置绑定的收款户名、账号,此时需能够选择未被绑定的所有剩余收款户名、账号
    if (this.data.accountOptions.length == 0) {
      this.setData({
        accountOptions: this.data.originAccountOptions
      })
      // this.setData({
      //   accountOptions: this.data.originAccountOptions.filter((account)=>{
      //     return this.data.haveBeenBind.indexOf(account.fundId) < 0
      //   })
      // })
    }
    if (this.data.accountOptions.length > 1) {
      if (e=='confirm') {
        console.log("confirm")
        this.setData({
          accountIndex: ''
        })
      } else {
        console.log("not confirm")
        this.data.accountOptions.forEach((item,index) => {
          if(item.accountName == selectedAccountName) {
            this.setData({
              accountIndex: index
            })
          }
        })
      }
    }
    // 若候选列表仅有一条记录，则自动为用户选择该记录
    if (this.data.accountOptions.length == 1) {
      this.setData({
        accountIndex: 0
      })
    }
    // 解除打开收款户名、账号选择弹窗的限制
    this.setData({
      enableAccountPicker: true
    })
  },
  onInput(event) {

  },
  onMoneyInput(e) {
    // console.log(e.currentTarget.dataset.type)
    let type = e.currentTarget.dataset.type
    if (e.detail) {
      let num = e.detail.toString()
      num = (num.match(/^\d*(\.?\d{0,2})/g)[0]) || ''
      this.setData({
        [type]: num
      })
    } else {
      this.setData({
        [type]: '',
      })
    }
  },
  onChange({ detail }) {
    this.setData({ addFlag: detail });
  },
  clickSave() {
    if (!this.validFrm()) {
      return
    }
    if (this.data.submitting) {
      return
    }
    var that = this
    var queryData = {
      id: this.data.id,
      qrcodeNo: this.data.qrcodeNo,
      accountId: this.data.accountOptions[this.data.accountIndex].id,
      inputAmount: this.data.inputAmount,
      realCashAmount: this.data.realCashAmount,
      payDate: this.data.currentStr.replace(/-/g, ''), // 8位
      fundType: !this.data.showMoreField ? 0 : this.data.addFlag ? 2 : 1,
      fundId: this.data.abstractOptions[this.data.abstractIndex].id,
      fundName: this.data.more ? this.data.more : '',
      actPayerId: this.data.staffIndex != this.data.staffOptions.length - 1 ? this.data.staffOptions[this.data.staffIndex].id : '',
      jjCode:this.data.jjCode
    }
    console.log(queryData)
    if (JSON.stringify(this.data.bagInfo) !== '{}') {
      this.setData({ submitting: true })
      // 编辑箱包
      request('/smsk/wechat/baginfo/update', 'POST', queryData).then(res => {
        // console.log(res.data)
        this.setData({ submitting: false })
        if (res.data.code === 0) {
          wx.showToast({
            title: '保存成功',
            icon: 'success'
          })
          setTimeout(() => {
            wx.setStorageSync('tempTabId', '0')
            wx.navigateBack({
              delta: 1,
            })
          }, 1500)
        } else {
          // console.log(res.data)
          wx.showToast({
            title: '保存失败',
            icon: 'error'
          })
        }
      })
      // 2022.1.14变更 改为仅保存
      // Dialog.confirm({
      //   message: '是否直接发送银行',
      //   confirmButtonText: '是，确认订单',
      //   cancelButtonText: '否，仅保存',
      //   confirmButtonColor: '#00A7DC',
      //   customStyle: 'border-radius: 5px;',
      //   closeOnClickOverlay: true
      // })
      //   .then(() => {
      //     request('/smsk/wechat/baginfo/update', 'POST', queryData).then(res => {
      //       // 保存了箱包，跳转确认箱包
      //       if (res.data.code === 0) {
      //         let bagList = []
      //         bagList.push(res.data.data)
      //         wx.setStorageSync('tempBagList', bagList)
      //         wx.redirectTo({
      //           url: '/pages/cashService/operator/orderConfirm/orderConfirm',
      //         })
      //       } else {
      //         console.log(res.data)
      //       }
      //     })
      //   })
      //   .catch(() => {
      //     request('/smsk/wechat/baginfo/update', 'POST', queryData).then(res => {
      //       // console.log(res.data)
      //       if (res.data.code === 0) {
      //         wx.showToast({
      //           title: '保存成功',
      //           icon: 'success'
      //         })
      //         setTimeout(() => {
      //           wx.navigateBack({
      //             delta: 1,
      //           })
      //         }, 1500);
      //       } else {
      //         // console.log(res.data)
      //         wx.showToast({
      //           title: '保存失败',
      //           icon: 'error'
      //         })
      //       }
      //     })
      //     // wx.navigateBack()
      //   });
    } else {
      // 创建箱包
      request('/smsk/wechat/baginfo/create', 'POST', queryData).then(res => {
        // console.log(res.data)
        if (res.data.code === 0) {
          wx.showToast({
            title: '保存成功',
            icon: 'success'
          })
          setTimeout(() => {
            wx.setStorageSync('tempTabId', '0')
            wx.navigateBack({
              delta: 1,
            })
          }, 1500)
        } else {
          // console.log(res.data)
          wx.showToast({
            title: '保存失败',
            icon: 'error'
          })
        }
      })
      // 2022.1.14变更 改为仅保存
      // Dialog.confirm({
      //   message: '是否直接发送银行',
      //   confirmButtonText: '是，确认订单',
      //   cancelButtonText: '否，仅保存',
      //   confirmButtonColor: '#00A7DC',
      //   customStyle: 'border-radius: 5px;',
      //   closeOnClickOverlay: true
      // })
      //   .then(() => {
      //     request('/smsk/wechat/baginfo/create', 'POST', queryData).then(res => {
      //       console.log(res.data)
      //       // 保存了箱包，跳转确认箱包
      //       if (res.data.code === 0) {
      //         let bagList = []
      //         bagList.push(res.data.data)
      //         wx.setStorageSync('tempBagList', bagList)
      //         wx.redirectTo({
      //           url: '/pages/cashService/operator/orderConfirm/orderConfirm',
      //         })
      //       } else {
      //         console.log(res.data)
      //       }
      //     })
      //   })
      //   .catch(() => {
      //     request('/smsk/wechat/baginfo/create', 'POST', queryData).then(res => {
      //       // console.log(res.data)
      //       if (res.data.code === 0) {
      //         wx.showToast({
      //           title: '保存成功',
      //           icon: 'success'
      //         })
      //         setTimeout(() => {
      //           wx.navigateBack({
      //             delta: 1,
      //           })
      //         }, 1500);
      //       } else {
      //         // console.log(res.data)
      //         wx.showToast({
      //           title: '保存失败',
      //           icon: 'error'
      //         })
      //       }
      //     })
      //   });
    }
  },

  validFrm() {
    if (this.data.accountIndex < 0) {
      this.showToast('请选择户名或账号')
      return false
    }
    if (!this.data.inputAmount) {
      this.showToast('请输入交款金额')
      return false
    }
    if (!this.data.realCashAmount) {
      this.showToast('请输入现金实物金额')
      return false
    }
    // 现金实物金额分币不为零时，不允许保存
    if (this.data.realCashAmount.toString().split(".")[1] && this.data.realCashAmount.toString().split(".")[1].length == 2 && this.data.realCashAmount.toString().split(".")[1][1] != '0') {
      Dialog.alert({
        message: '“现金实物金额”是您放入专用袋中的现金金额，没有分币，请修改',
      }).then(() => {
        // on close
      });
      return false
    }
    if (!this.data.currentStr) {
      this.showToast('请选择日期')
      return false
    }
    if (this.data.abstractIndex === '') {
      this.showToast('请选择项目')
      return false
    }
    if ((this.data.abstractIndex === this.data.abstractOptions.length - 1) && !this.data.more) {
      this.showToast('请填写项目')
      return false
    }
    return true
  },
  showToast(str) {
    wx.showToast({
      title: str,
      icon: 'none'
    })
  },
  /**
   * 获取操作员
   */
  fetchStafflist() {
    var that = this
    request('/smsk/wechat/baginfo/staff', 'GET', { staffName: '' }).then(res => {
      // console.log(res.data)
      if (res.data.code === 0) {
        var tempIndex = ''
        let temparr = res.data.data
        temparr.push({ staffName: wx.getStorageSync('userInfo').userName })
        // console.log(temparr)
        // 如果是编辑箱包模式，找到所选账号在选项中的index用于选择器及展示
        if (that.data.bagInfo && that.data.bagInfo.actPayerId != null) {
          tempIndex = temparr.findIndex((item) => {
            return item.id === that.data.bagInfo.actPayerId
          })
          if (tempIndex == -1) {
            tempIndex = temparr.length - 1
          }
        } else {
          tempIndex = temparr.length - 1
        }
        this.setData({
          staffOptions: temparr,
          staffIndex: tempIndex
        })
      } else {
      }
    })
  }
})